<template>
  <a-card>
    <a-steps class="item" :current="currentTab" align-center finish-status="success">
      <a-step title="商品信息" />
      <a-step title="商品详情" />
      <a-step title="其他设置" />
      <!--<a-step title="规格设置" />-->
    </a-steps>
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ style: { width: '80px' } }">
      <a-row v-show="currentTab === 0" :gutter="24">
        <a-col v-bind="gridops">
          <a-form-item label="商品名称：" name="storeName">
            <a-input v-model:value="form.storeName" maxlength="249" placeholder="请输入商品名称" :disabled="isDisabled" />
          </a-form-item>
        </a-col>
        <a-col v-bind="gridops">
          <a-form-item label="商品分类：" name="cateIds">
            <a-cascader v-model:value="form.cateIds" :options="merCateList"
              :field-names="{ label: 'name', value: 'id', children: 'child' }" clearable class="selWidth"
              :show-all-levels="false" :disabled="isDisabled" />
          </a-form-item>
        </a-col>
        <a-col v-bind="gridops">
          <a-form-item label="商品关键字：" name="keyword">
            <a-input v-model:value="form.keyword" placeholder="请输入商品关键字" :disabled="isDisabled" />
          </a-form-item>
        </a-col>
        <a-col v-bind="gridops">
          <a-form-item label="单位：" name="unitName">
            <a-input v-model:value="form.unitName" placeholder="请输入单位" :disabled="isDisabled" />
          </a-form-item>
        </a-col>
        <a-col v-bind="gridops">
          <a-form-item label="商品简介：" name="storeInfo">
            <a-input v-model:value="form.storeInfo" type="textarea" maxlength="250" :rows="3" placeholder="请输入商品简介"
              :disabled="isDisabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="商品轮播图：" name="sliderImages">
            <upload-img v-model:value="form.sliderImages" :limit="10" placeholder="商品轮播图：" />
          </a-form-item>
        </a-col>

        <a-col :xs="18" :sm="18" :md="18" :lg="12" :xl="12">
          <a-form-item label="运费模板：" name="tempId">
            <a-select v-model:value="form.tempId" placeholder="请选择" class="mr20" :disabled="isDisabled"
              style="width:100%;">
              <a-select-option v-for="item in shippingList" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xs="6" :sm="6" :md="6" :lg="12" :xl="12" class="mb10">
          <a-button v-show="!isDisabled" class="mr15" @click="addTem">运费模板</a-button>
        </a-col>
        <a-col :span="24">
          <a-form-item label="商品规格：" props="specType">
            <a-radio-group v-model:value="form.specType" :disabled="isDisabled" @change="onChangeSpec(form.specType)">
              <a-radio :value="false" class="radio">单规格</a-radio>
              <a-radio :value="true">多规格</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="佣金设置：" props="isSub">
            <a-radio-group v-model:value="form.isSub" :disabled="isDisabled" @change="onChangetype(form.isSub)">
              <a-radio :value="true" class="radio">单独设置</a-radio>
              <a-radio :value="false">默认设置</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <!-- 多规格添加-->
        <a-col v-if="form.specType && !isDisabled" :span="24" class="noForm">
          <a-form-item label="选择规格：" name="">
            <div class="acea-row flex middle">
              <a-select v-model:value="form.selectRule" style="width:50%;">
                <a-select-option v-for="item in ruleList" :key="item.id" :value="item.id">
                  {{ item.ruleName }}
                </a-select-option>
              </a-select>
              <div class="cell-main flex middle ml10">
                <a-button type="primary" class="mr20" @click="confirm">确认</a-button>
                <a-button class="mr15" @click="addRule">添加规格</a-button>
              </div>
            </div>
          </a-form-item>
          <a-col v-for="(item, index) in form.attr" :key="index" :span="24" class="noForm">
            <a-form-item>
              <div class="attr-box">
                <span class="mr5">{{ item.attrName }}</span>
                <CloseCircleOutlined @click="handleRemove(index)" />
              </div>
              <div class="flex middle">
                <a-tag v-for="(j, indexn) in item.attrValue" :key="indexn" closable size="medium"
                  :disable-transitions="false" class="mb5 mr10" @close="handleClose(item.attrValue, indexn)">
                  {{ j }}
                </a-tag>
                <a-input v-if="item.inputVisible" ref="saveTagInput" v-model:value="item.attrsVal" class="tagInput"
                  size="small" @blur="createAttr(item.attrsVal, index)" />
                <a-button v-else class="button-new-tag" size="small" @click="showInput(item)">+ 添加</a-button>
              </div>
            </a-form-item>
          </a-col>
          <a-row v-if="isBtn" :gutter="24" justify="start" align="top">
            <a-col :span="7">
              <a-form-item label="规格：">
                <a-input v-model:value="attrsName" placeholder="请输入规格" />
              </a-form-item>
            </a-col>
            <a-col :span="7">
              <a-form-item label="规格值：">
                <a-input v-model:value="attrsVal" placeholder="请输入规格值" />
              </a-form-item>
            </a-col>
            <a-col :span="3">
              <a-button type="primary" class="mr10" @click="createAttrName">确定</a-button>
            </a-col>
            <a-col :span="3">
              <a-button @click="offAttrName">取消</a-button>
            </a-col>
          </a-row>
          <a-form-item v-if="!isBtn">
            <a-button type="primary" class="mr15" @click="addBtn">添加新规格</a-button>
          </a-form-item>
        </a-col>
        <!-- 批量设置-->
        <a-col v-if="form.specType && !isDisabled" :span="24" class="noForm">
          <a-form-item label="批量设置：">
            <brokerPop :is-sub="form.isSub" :goods="goods" :isboth="true" @uploadAttrD="uploadAttrD" />
          </a-form-item>
          <a-form-item>
            <goodPop :other-col="manyTabDate" :is-sub="form.isSub" :goods="ManyAttrValue" :isboth="true"
              @delTable="delTable" />
          </a-form-item>
        </a-col>
        <!-- 单规格表格-->
        <a-col v-if="!form.specType" :span="24" class="noForm">
          <brokerPop :is-sub="form.isSub" :goods="goods" @uploadAttrD="uploadAttrD" />
        </a-col>
      </a-row>
      <!-- 商品详情-->
      <a-row v-show="currentTab === 1 && !isDisabled">
        <a-col :span="24">
          <a-form-item label="商品详情：">
            <WangEditor :height="350" :value="form.content" @input="setContent" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row v-show="currentTab === 1 && isDisabled">
        <a-col :span="24">
          <a-form-item label="商品详情：">
            <span v-html="form.content || '无'" />
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 其他设置-->
      <a-row v-show="currentTab === 2">
        <a-col :span="24">
          <a-col v-bind="gridops">
            <a-form-item label="排序：">
              <a-input-number v-model:value="form.sort" :min="0" placeholder="请输入排序" :disabled="isDisabled" />
            </a-form-item>
          </a-col>
          <a-col v-bind="gridops">
            <a-form-item label="积分：">
              <a-input-number v-model:value="form.giveIntegral" :min="0" placeholder="请输入排序" :disabled="isDisabled" />
            </a-form-item>
          </a-col>
          <a-col v-bind="gridops">
            <a-form-item label="虚拟销量：">
              <a-input-number v-model:value="form.ficti" :min="0" placeholder="请输入排序" :disabled="isDisabled" />
            </a-form-item>
          </a-col>
        </a-col>
        <a-col :span="24">
          <a-form-item label="商品推荐：">
            <a-checkbox-group v-model:value="checkboxGroup" size="small" :disabled="isDisabled" @change="onChangeGroup">
              <a-checkbox v-for="(item, index) in recommend" :key="index" :value="item.value">{{ item.name }}</a-checkbox>
            </a-checkbox-group>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="活动优先级：">
            <div class="flex middle">
              <div v-for="item in form.activity" :key="item" :disabled="isDisabled" class="color-item"
                :class="activity[item]" draggable="true" @dragstart="handleDragStart($event, item)"
                @dragover.prevent="handleDragOver($event, item)" @dragenter="handleDragEnterFont($event, item)"
                @dragend="handleDragEnd($event, item)">
                {{ item }}
              </div>
              <div class="tip">可拖动按钮调整活动的优先展示顺序</div>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="优惠券：" class="proCoupon">
            <div class="acea-row">
              <a-tag v-for="(tag, index) in form.coupons" :key="index" class="mr10 mb10" :closable="!isDisabled"
                :disable-transitions="false" @close="handleCloseCoupon(tag)">
                {{ tag.name }}
              </a-tag>
              <!-- <span v-if="form.couponIds == null">无</span> -->
              <a-button v-if="!isDisabled" class="mr15" @click="addCoupon">选择优惠券</a-button>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item>
        <a-button v-show="currentTab > 0" class="submission priamry_border" @click="handleSubmitUp">上一步</a-button>
        <a-button v-show="currentTab < 2" type="primary" class="submission" @click="handleSubmitNest">
          下一步
        </a-button>
        <a-button v-show="(currentTab === 2 || curId) && !isDisabled" type="primary" class="submission"
          @click="handleSubmit">
          提交
        </a-button>
      </a-form-item>
    </a-form>

    <attrPop v-model:visible="showPop" :type="1" :data="{}" @change="dealAttr" />
    <CreatTemplates ref="addTemplates" v-model:visible="showCreat" :data="{}" @change="getShippingList" />
    <a-modal v-model:visible="open" :width="900" title="优惠券" @ok="changeCoupon">
      <couponList handle="wu" :keyNum="keyNum + 1" :coupons="form.coupons" @getCouponId="getCouponId" />
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
import { categoryApi, goodDesignList, marketingSendApi, shippingTemplatesList, storeproductAddup, storeproductinfo, templateListApi } from './api';
import { storeproduct, type Istoreproduct, defaultGood } from './entity';
import { validReg } from '@/utils/validate';
import attrPop from './attr/detail.vue';
import { setDomain, replaceImgSrcHttps } from '@/utils';
import CreatTemplates from '@/views/deliverGoods/freightSet/detail.vue'
import { useFormValid } from "@/views/login/useLogin";
import brokerPop from './brokerPop.vue';
import goodPop from './goodPop.vue';
import couponList from '@/components/couponList.vue';
let route = useRoute()
let router = useRouter()
const gridops = { xl: 12, lg: 12, md: 12, sm: 24, xs: 24 }
const title = computed(() => route.query.id ? '编辑商品' : '新增商品')
let shippingList = $ref([{ id: '', name: '' }])
let merCateList = $ref([{ id: '', name: '' }])
const { formRef, } = useDialog({ validCallback: handleSubmit })
const { validForm } = useFormValid(formRef);
let currentTab = $ref(0)
let form = $ref(new storeproduct())
let isDisabled = $ref(false)
let curId = $ref('')
let isAttr = $ref(false)
let showPop = $ref(false)
let showAll = $ref(false)
let isBtn = $ref(false)
let attrsName = $ref('')
let checkboxGroup = $ref<string[]>([])
let attrsVal = $ref('')
let showCreat = $ref(false)
let id = $ref('')
let keyNum = $ref(0)
let selectCoupons = $ref<any[]>([])
let manyTabDate = $ref<string[]>([])
const activity = { '默认': 'red', '秒杀': 'blue', '砍价': 'green', '拼团': 'yellow' }
const tags_store = useTagsStore();
let ruleList = $ref([{ id: '', ruleName: '', ruleValue: [{ detail: '', value: '' }] }])
onMounted(() => {
  let { id, edt } = route.query
  curId = id as string
  isDisabled = !!edt
  if (id) {
    setTagsViewTitle()
  }
  getCategorySelect()
  getShippingList()
  getGoodsType()
})
let defaultItem = $ref(new defaultGood())
let goods = computed(() => [{ ...defaultItem }])
let OneattrValue = $ref([{ ...defaultItem }])
let ManyAttrValue = $ref([{ ...defaultItem }])
watch(
  () => form.attr,
  (val) => {
    if (form.specType && isAttr) {
      dealtable(val)
    }
  }
)

let open = $ref(false)
// 商品分类；
async function getCategorySelect() {
  let res = await categoryApi({ status: -1, type: 1 })
  merCateList = filerMerCateList(res)
  let newArr: any[] = [];
  res.forEach((value: any, index: number) => {
    newArr[index] = value;
    if (value.child) newArr[index].child = value.child.filter(item => item.status === true)
  }) //过滤商品分类设置为隐藏的子分类不出现在树形列表里
  merCateList = filerMerCateList(newArr)
}
async function getInfo(id: string) {
  let res = await storeproductinfo(id)
  form.setProps(res)
  form.image = setDomain(res.image)
  form.sliderImages = JSON.parse(res.sliderImage)
  form.cateIds = res.cateId.split(',')
  form.content = replaceImgSrcHttps(res.content)
  form.activity = res.activityStr ? res.activityStr.split(',') : ['默认', '秒杀', '砍价', '拼团']
  let { list } = await marketingSendApi({ type: 3 })
  form.coupons = list
  productGetRule()
  if (res.specType) {
    form.attr = res.attr.map((item: any) => {
      return {
        attrName: item.attrName,
        attrValue: item.attrValues.split(',')
      }
    })
    ManyAttrValue = res.attrValue;
  }
}
function filerMerCateList(treeData: any) {
  return treeData.map((item: any) => {
    if (!item.child) {
      item.disabled = true
    }
    item.label = item.name
    return item
  })
}
function onChangeGroup() {
  form.isGood = checkboxGroup.includes('isGood')
  form.isBenefit = checkboxGroup.includes('isBenefit')
  form.isBest = checkboxGroup.includes('isBest')
  form.isNew = checkboxGroup.includes('isNew')
  form.isHot = checkboxGroup.includes('isHot')
}
// 移动      },
let dragging = $ref<any>()
function handleDragStart(e: any, item: any) {
  if (!isDisabled) dragging = item;
}
function handleDragEnd(e: any, item: any) {
  if (!isDisabled) dragging = null
}
function handleDragOver(e: any, item: any) {
  if (!isDisabled) e.dataTransfer.dropEffect = 'move'
}
function handleSubmitUp() {
  // currentTab --
  if (currentTab-- < 0) currentTab = 0;
}

function delTable(i: number) {
  ManyAttrValue.splice(i, 1)
}
async function handleSubmitNest() {
  const data = await validForm();
  if (!data) return;
  if (currentTab++ > 2) currentTab = 0;
}
function uploadAttrD(obj: any) {
  let { isboth, attrValue, ...temp } = obj
  if (obj.isboth) {
    ManyAttrValue = ManyAttrValue.map(e => {
      return { ...e, ...temp }
    })
  } else {
    OneattrValue = [{ ...OneattrValue, ...temp }]
  }
}
function dealtable(val: any) {
  const tmp: string[] = []
  form.attr.forEach((o, i) => {
    tmp.push(o.attrName)
  });
  ManyAttrValue = attrFormat(val);
  manyTabDate = tmp
}
function attrFormat(arr: any[]) {
  let ret: any[] = []
  let defaultAttr = { image: '', price: 0, cost: 0, otPrice: 0, stock: 0, barCode: '', weight: 0, volume: 0, brokerage: 0, brokerage_two: 0 }
  if (arr.length > 1) {
    let spec1 = arr[0]
    let spec2 = arr[1]
    spec1.attrValue.forEach((e: any) => {
      spec2.attrValue.forEach((item: any) => {
        ret.push({
          ...defaultAttr, [spec1.attrName]: e, [spec2.attrName]: item, attrValue: {
            [spec1.attrName]: e, [spec2.attrName]: item
          }
        })
      })
    })
  } else {
    let spec1 = arr[0]
    spec1.attrValue.forEach((e: any) => {
      ret.push({
        ...defaultAttr, [spec1.attrName]: e, attrValue: { [spec1.attrName]: e, }
      })
    })
  }

  return ret
}
function handleSubmit() {
  onChangeGroup()
  let attr = [], attrValue = []
  if (form.specType && form.attr.length < 1) return AntMessage.warning("请填写多规格属性！");
  form.cateId = form.cateIds.join(',')
  form.sliderImage = JSON.stringify(form.sliderImages)
  if (form.specType) {
    attrValue = ManyAttrValue.map(e => { e.attrValue = JSON.stringify(e.attrValue); return e })
    attr = form.attr.map((item) => {
      return {
        attrName: item.attrName,
        id: item.id,
        attrValues: item.attrValue?.join(','),
      }
    })
    for (var i = 0;i < form.attrValue.length;i++) {
      attrValue[i].id = 0
      attrValue[i].productId = 0
      attrValue[i].attrValue = JSON.stringify(form.attrValue[i].attrValue)
    }
  } else {
    attr = [{ attrName: '规格', attrValues: '默认', id: route.params.id ? form.attr[0].id : 0 }]
    OneattrValue.map(item => {
      item.attrValue = JSON.stringify({ '规格': '默认' })
    })
    attrValue = OneattrValue
  }

  storeproductAddup({ ...form, attr, attrValue }).then(() => {
    AntMessage.success('保存成功')
    router.push({ path: '/store/index' });
  })
}
function getCouponId(rows: any[]) {
  selectCoupons = rows
}
function changeCoupon() {
  open = false
  form.coupons = selectCoupons
  form.couponIds = selectCoupons.map((e: any) => e.id)
}
function handleDragEnter(e: any, item: any) {
  if (!isDisabled) {
    e.dataTransfer.effectAllowed = 'move'
    if (item === dragging) {
      return
    }
    const newItems = [...form.sliderImages]
    const src = newItems.indexOf(dragging)
    const dst = newItems.indexOf(item)
    newItems.splice(dst, 0, ...newItems.splice(src, 1))
    form.sliderImages = newItems;
  }
}
function handleDragEnterFont(e: any, item: any) {
  if (!isDisabled) {
    e.dataTransfer.effectAllowed = 'move'
    if (item === dragging) {
      return
    }
    const newItems = [...form.activity]
    const src = newItems.indexOf(dragging)
    const dst = newItems.indexOf(item)
    newItems.splice(dst, 0, ...newItems.splice(src, 1))
    form.activity = newItems;
  }
}
function setTagsViewTitle() {
  const title = isDisabled ? '商品详情' : '编辑商品'
  route.meta.title = `${title}-${id}`
  tags_store.updateView(route)
}
function addTem() {
  showCreat = true;
}
function handleCloseCoupon(tag: string) {
  isAttr = true
  form.coupons.splice(form.coupons.indexOf(tag), 1)
  form.couponIds.splice(form.couponIds.indexOf(tag.id), 1)
}
function addCoupon() {
  open = true

}
// 运费模板；
async function getShippingList() {
  let { list } = await shippingTemplatesList({ page: 1, limit: 999 })
  shippingList = list

}
let recommend = $ref([{ name: '', value: '' }])
async function getGoodsType() {
  /** 让商品推荐列表的name属性与页面设置tab的name匹配**/
  let { list } = await goodDesignList({ gid: 70 })
  let arr: any[] = [], arr1: any[] = []
  const listArr = [{ name: '是否热卖', value: 'isGood', type: '' }];
  let typeLists = [
    { name: '', value: 'isHot', type: '2' },   //热门榜单 
    { name: '', value: 'isBenefit', type: '4' }, //促销单品
    { name: '', value: 'isBest', type: '1' }, //精品推荐
    { name: '', value: 'isNew', type: '3' }]; //首发新品
  list.forEach((item: any) => {
    let obj = { value: JSON.parse(item.value), id: item.id, gid: item.id, status: item.status, };
    arr.push(obj);
  })
  arr.forEach((item1) => {
    let obj1 = { name: item1.value.fields[1].value, type: item1.value.fields[3].value, status: item1.status, };
    arr1.push(obj1);
  })
  typeLists.forEach((item) => {
    arr1.forEach((item1) => {
      if (item.type == item1.type) {
        listArr.push({
          name: item1.name,
          value: item.value,
          type: item.type
        })
      }
    })
  })
  recommend = listArr
}
function onChangeSpec(num: boolean) {
  isAttr = true;
  if (num) productGetRule()
}
function onChangetype(num: boolean) {
  if (!num) {
    OneattrValue = OneattrValue.map(e => {
      e.brokerage = ''
      e.brokerageTwo = ''
      return e
    })
    ManyAttrValue = ManyAttrValue.map(e => {
      e.brokerage = ''
      e.brokerageTwo = ''
      return e
    })

  }
}
async function productGetRule() {
  let { list } = await templateListApi({ page: 1, limit: 999, keywords: '' })
  ruleList = list.map((e: any) => {
    e.ruleValue = JSON.parse(e.ruleValue)
    return e
  })

}
function dealAttr(obj: any) {
  showPop = false
  productGetRule()
}
function addRule() {
  showPop = true
}
// 删除
function handleRemove(index: number) {
  form?.attr.splice(index, 1)
}
function handleClose(item: any, index: number) {
  item.splice(index, 1)
}
function showInput(item: any) {
  item.inputVisible = true
}
function showAllSku() {

}
// 添加按钮
function addBtn() {
  isBtn = true
}
// 取消
function offAttrName() {
  isBtn = false
}
// 添加属性
function createAttr(num: string, idx: number) {
  if (num) {
    form.attr[idx].attrValue?.push(num)
    form.attr[idx].attrsVal = ''
    form.attr[idx].inputVisible = false
  } else {
    AntMessage.warning('请添加属性');
  }
}
// 添加规则名称
function createAttrName() {
  if (attrsName && attrsVal) {
    const data = {
      attrName: attrsName,
      attrValue: [
        attrsVal
      ],
      attrsVal: '',
      inputVisible: false
    }
    form.attr.push(data)
    attrsName = '';
    attrsVal = '';
    isBtn = false;
  } else {
    AntMessage.warning('请添加规格名称');
  }
}
function confirm() {
  isAttr = true
  if (!form.selectRule) {
    return AntMessage.warning('请选择属性')
  }
  const data = []
  ruleList.forEach(item => {
    if (item.id === form.selectRule) {
      item.ruleValue.forEach(i => {
        data.push({
          attrName: i.value,
          attrValue: i.detail,
        })
      })
    }
    form.attr = data;
  });
}
watchEffect(() => {
  if (route.query.id) {
    id = route.query.id as string
    getInfo(id)
  }
})

function setContent(html: string) {
  form.content = html
}
const rules = {
  articleName: [validReg('required', '请输入用户名')]
}

onMounted(() => {
})
const emit = defineEmits(['change'])


function reset() {
  form = new storeproduct()
}
</script>

<style lang="scss">
.color-item {
  height: 30px;
  line-height: 30px;
  padding: 0 10px;
  color: #fff;
  margin-right: 10px;
}

.color-item.blue {
  background-color: #1E9FFF;
}

.color-item.yellow {
  background-color: rgb(254, 185, 0);
}

.color-item.green {
  background-color: #009688;
}

.color-item.red {
  background-color: #ed4014;
}
</style>
